package com.hundsun.yr.universal.p2p.presenter.impl;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.common.PackageUtils;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.utils.HSJSONTools;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog.HSDialogOnItemClickListener;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.HsApplication;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Container;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.base.RequestInteractor;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestInteractorImpl;
import com.hundsun.yr.universal.p2p.listener.BaseMultiLoadedListener;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.ui.activity.MainActivity;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.BaseItemView;
import com.hundsun.yr.universal.p2p.view.base.BaseTabView;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

/**
 * todo 检测版本升级
 *
 * @version V1.0
 * @Title: CheckVersionPresenterImpl.java
 * @Description: 检测版本升级
 * @date 2016-3-24
 * @author:hu.zepeng
 * @email:huzp@hundsun.com
 */
public class CheckVersionPresenterImpl implements RequestPresenter, BaseMultiLoadedListener<String>, HSDialogOnItemClickListener {

    /**
     * 上下文
     */
    private Context mContext = null;
    /**
     * 更多页面View
     */
    private BaseItemView mView = null;
    /**
     * 启动页面View
     */
    private BaseTabView mBaseTabView = null;
    private RequestInteractor mRequestInteractor = null;
    /**
     * 当前版本号
     */
    private String versionName;
    /**
     * 最低版本
     **/
    private String miniVersion;
    /**
     * 最新版本号
     */
    private String currentVersion;
    /**
     * 下载ID
     */
    private Long downloadId;
    /**
     * 下载器
     */
    private DownloadManager downloadManager;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
    /**
     * 下载状态观察者
     */
    private DownloadChangeObserver downloadObserver;
    /**
     * 下载进度条
     */
    private ProgressDialog progress;
    /**
     * 下载地址
     */
    private String downloadUrl = null;
    /**
     * 下载弹窗
     **/
    private HSDialog dialog_down = null;
    /**
     * 更新弹窗
     **/
    private HSDialog dialog_update = null;
    /**
     * 是否是首页
     **/
    private boolean isHome = false;
    /**
     * 是否强制升级
     **/
    private boolean if_force = false;

    private String DOWNLOADPATH = "/apk/";
    private static int REQUESTPERMISSION = 110;
    Activity activity = null;

    //--------------------------------------------------------------------------------------------华丽的分割线

/*    private String versionCode;
    private String serverVersion;
    private String minVersion = "1";*/
    public HSSharedPreferences mConfigSP;
    private ViewTreeObserver mViewTreeObserver;

    public CheckVersionPresenterImpl(Context context, BaseItemView view,Activity activity) {
        if (null == view) {
            throw new IllegalArgumentException("Constructor's parameters must not be Null");
        }
        this.mContext = context;
        this.mView = view;
        this.isHome = false;
        this.mRequestInteractor = new StringRequestInteractorImpl(this);
        this.activity = activity;
        mConfigSP = new HSSharedPreferences(mContext, Config.SPPath.file_configInfo);
    }

    public CheckVersionPresenterImpl(Context context, BaseTabView baseTabView,Activity activity) {
        if (null == baseTabView) {
            throw new IllegalArgumentException("Constructor's parameters must not be Null");
        }
        this.mContext = context;
        this.mBaseTabView = baseTabView;
        this.isHome = true;
        this.mRequestInteractor = new StringRequestInteractorImpl(this);
        this.activity = activity;
        mConfigSP = new HSSharedPreferences(mContext, Config.SPPath.file_configInfo);
    }

    @Override
    public void initialized() {
        versionName = PackageUtils.getVersionName(mContext);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                checkVersion();
            }
        }, 500);
    }

    /**
     * 验证当前版本号，和服务端版本号
     */
    public void checkVersion() {
        currentVersion = mConfigSP.getShareProf("server_version");
        miniVersion = mConfigSP.getShareProf("min_version");
        Log.e("min_version",currentVersion+">>>>"+miniVersion);
        if (miniVersion == null || currentVersion == null){
            return;
        }

        if (TextUtils.equals(currentVersion, versionName)) {
            if (!isHome) {
//                new HSToast(mContext).showToast(mContext.getString(R.string.no_update));
            }
            // 强制更新
        } else {
            if (compareVersion(miniVersion, currentVersion)) {
                if (!isHome) {
//                    new HSToast(mContext).showToast(mContext.getString(R.string.no_update));
                }
            } else {
                if (compareVersion(miniVersion, versionName)) {
                        showUpdataDialog(true);
                    // 非强制更新
                } else if (compareVersion(currentVersion, versionName)) {
                        showUpdataDialog(false);
                }
            }
        }
    }

    /**
     * 结束页面
     */
    public void onDestroy() {

    }

    /**
     * 获取服务器版本号成功后处理
     */
    @Override
    public void onSuccess(String task_name, int event_tag, String data) {
//		System.out.println(data);
        if (mView != null) mView.closeProgress();
        JSONObject obj = HSJSONTools.getJsonObject(data);
        String errorCode = HSJSONTools.getString(obj, "errorCode");

        if (TextUtils.equals(errorCode, Constants.REQUESTCODE_0000)) {
            Container.getInstance().isCheckVersion = true;
            String object = HSJSONTools.getString(obj, "busiObject");
            // 最低版本
            miniVersion = HSJSONTools.getString(object, "miniVersion");
            // 当前版本
            currentVersion = HSJSONTools.getString(object, "currentVersion");
//			downloadUrl= HSJSONTools.getString(object, "downloadUrl");

            // 不更新
            if (TextUtils.equals(currentVersion, versionName)) {
                if (!isHome) {
                    new HSToast(mContext).showToast(mContext.getString(R.string.no_update));
                }
                // 强制更新
            } else {
                if (compareVersion(miniVersion, currentVersion)) {
                    if (!isHome) {
                        new HSToast(mContext).showToast(mContext.getString(R.string.no_update));
                    }
                } else {
                    if (compareVersion(miniVersion, versionName)) {
                        showUpdataDialog(true);
                        // 非强制更新
                    } else if (compareVersion(currentVersion, versionName)) {
                        showUpdataDialog(false);
                    }
                }
            }

        } else {
            new HSToast(mContext).showToast(HSJSONTools.getString(obj, "errorMsg"));
        }
    }

    /**
     * 获取服务器版本号异常后处理
     */
    @Override
    public void onException(String task_name, String msg) {
        if (mView != null) mView.closeProgress();
        new HSToast(mContext).showToast(msg);
        if (isHome) mBaseTabView.initializeError(task_name, msg);

    }

    /**
     * 调用后台接口
     */
    @Override
    public void loadingData(final String task_name, final String url, final int event_tag,
                            final HashMap<String, String> params, final boolean isSwipeRefresh) {

        if (NetUtils.isNetworkConnected(mContext)) {
            if (!isHome) {
                mView.showProgress("");
            }
            mRequestInteractor.getRequestData(task_name, url, event_tag, params);
        } else {
            mView.closeProgress();
            new HSToast(mContext).showToast(R.string.common_no_network);
        }
    }

    @Override
    public void loadingData(String task_name, String url, int event_tag, HashMap<String, String> params, HashMap<String, String> header, boolean isSwipeRefresh) {

    }

    @Override
    public void loadingData(String task_name, String url, int event_tag, JSONObject params, HashMap<String, String> header, boolean isSwipeRefresh) {

    }

    /**
     * 比较版本号
     *
     * @param version1 版本1
     * @param version2 版本2
     * @return boolean
     */
    public boolean compareVersion(String version1, String version2) {

        if (!TextUtils.isEmpty(version1) && !TextUtils.isEmpty(version2)) {

            String[] version1Array = version1.split("\\.");
            String[] version2Array = version2.split("\\.");

            if (version1Array != null && version1Array.length > 2
                    && version2Array != null && version2Array.length > 2) {

                for (int i = 0; i < version1Array.length; i++) {

                    int v1 = Integer.parseInt(version1Array[i]);
                    int v2 = Integer.parseInt(version2Array[i]);

                    if (v1 > v2) {
                        return true;
                    } else if (v1 < v2) {
                        return false;
                    }
                }
            }
        }

        return false;
    }

    /**
     * @param isForce 是否强制更新
     * @Description 弹出下载对话框
     */
    protected void showUpdataDialog(boolean isForce) {
        this.if_force = isForce;
        String title = mContext.getString(R.string.update_title);
        String content;
        if (if_force) {
            content = mContext.getString(R.string.min_update_content, miniVersion, versionName);
        } else {
            content = mContext.getString(R.string.update_content, currentVersion);
        }

        dialog_update = new HSDialog(title, content,
                mContext.getString(R.string.cancel),
                mContext.getString(R.string.sure), mContext, this).setCancelable(!isForce);
        dialog_update.show();

    }

    /**
     * 判断网络环境(是否为wifi环境)
     */
    private void checkNetwork() {
        if (NetUtils.isNetworkAvailable(mContext)) {
            if (CommTool.isWifi(mContext)) {
                downloadNewVersion(DownloadManager.Request.NETWORK_WIFI);
            } else {
                dialog_update.setOnDismissListener(new HSDialog.HSDialogOnDismissListener() {
                    @Override
                    public void onDismiss(Object o) {
                        dialog_down = new HSDialog(mContext.getString(R.string.wifi_title), mContext.getString(R.string.wifi_content), mContext.getString(R.string.cancel), mContext.getString(R.string.sure), mContext, CheckVersionPresenterImpl.this);
                        dialog_down.show();
                    }
                });
            }
        } else {
            new HSToast(mContext).showToast(R.string.common_no_network);
        }
    }


    /**
     * @param @param network 网络环境
     * @Description 下载新版本
     */
    private void downloadNewVersion(int network) {
        if (CommTool.getChannel(mContext).equals("P1OJDiTB")){
            downloadUrl = mContext.getString(R.string.root_down_url) + "zwgt.apk";
        } else {
            downloadUrl = mContext.getString(R.string.root_down_url)  + CommTool.getChannel(mContext) + "zwgt.apk";
        }
        Uri uri = Uri.parse(downloadUrl);

        downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(uri);

        // 设置在什么网络情况下进行下载
        request.setAllowedNetworkTypes(network);
        // 设置通知栏标题
        request.setTitle("下载");
        request.setDescription("正在下载");
        request.setAllowedOverRoaming(false);
        request.setMimeType("application/vnd.android.package-archive");
        // 设置文件存放目录
//        try{
//            request.setDestinationInExternalPublicDir("P2P2.0-ZWGT", "P2P2.0-ZWGT.apk");
//        }catch (Exception e){
//            new HSToast(mContext).showToast("需要获取存储权限");
//            return;
//        }

        // 设置通知栏标题
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setDestinationInExternalPublicDir(DOWNLOADPATH, CommTool.getChannel(mContext) + currentVersion + "member.apk");

        progress = new ProgressDialog(mContext, ProgressDialog.THEME_HOLO_LIGHT);
        progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progress.setCancelable(false);
        progress.setTitle("正在更新");
        progress.setProgress(0);
        progress.setProgressNumberFormat("%1d kb/%2d kb");
        progress.show();

        downloadId = downloadManager.enqueue(request);

        mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        // 监听下载进度
        downloadObserver = new DownloadChangeObserver(null);
        mContext.getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);

    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (downloadId == reference) {
                if (progress != null) {
                    progress.dismiss();
                }

                if (if_force) {

                }
                if (mBaseTabView != null) {
                    onDestroy();
                }

                if (Build.VERSION.SDK_INT < 23) {
                    // 下载完成自动安装
                    Intent install = new Intent(Intent.ACTION_VIEW);
                    Uri downloadFileUri = downloadManager.getUriForDownloadedFile(downloadId);
                    install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(install);
                    HsApplication.getInstance().exitApp();
                } else {
//                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +DOWNLOADPATH+ CommTool.getChannel(mContext) + currentVersion + "zwgt.apk");
//                    if (file.exists()) {
//                        openFile(file, context);
//                    }
                    Intent install = new Intent(Intent.ACTION_VIEW);
                    Uri downloadFileUri = downloadManager.getUriForDownloadedFile(downloadId);
                    install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(install);
                    HsApplication.getInstance().exitApp();
                }
            }
        }

    };

    /**
     * @param downloadId 下载ID
     * @Description 查询下载状态
     */
    private void queryDownloadStatus(Long downloadId) {

        // 下载进度
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        Cursor c = downloadManager.query(query);

        if (c != null && c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            int reasonIdx = c.getColumnIndex(DownloadManager.COLUMN_REASON);
            int titleIdx = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
            int fileSizeIdx = c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
            int bytesDLIdx = c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
            String title = c.getString(titleIdx);
            int fileSize = c.getInt(fileSizeIdx) / 1024;
            int bytesDL = c.getInt(bytesDLIdx) / 1024;


//          Translate the pause reason to friendly text.    
            int reason = c.getInt(reasonIdx);
            StringBuilder sb = new StringBuilder();
            sb.append(title).append("\n");
            sb.append("reason:").append(reason).append("\n");
            sb.append("Downloaded ").append(bytesDL).append(" / ").append(fileSize);

            if (bytesDL > 0) {
                progress.setMax(fileSize);
                progress.setProgress(bytesDL);

            }

            switch (status) {
                // 下载暂停
                case DownloadManager.STATUS_PAUSED:
                    downloadManager.remove(downloadId);
                    break;
                // 待定状态
                case DownloadManager.STATUS_PENDING:
                    break;
                // 下载中
                case DownloadManager.STATUS_RUNNING:
                    break;
                // 下载成功
                case DownloadManager.STATUS_SUCCESSFUL:
                    break;
                // 下载失败
                case DownloadManager.STATUS_FAILED:
                    //清除已下载的内容，重新下载
                    downloadManager.remove(downloadId);
                    break;
                default:
                    if (progress != null) {
                        progress.dismiss();
                    }
                    downloadManager.remove(downloadId);
                    break;
            }

            if (DownloadManager.STATUS_RUNNING != status) {
                if (progress != null) {
                    progress.dismiss();
                }
            }
        }
    }

    @Override
    public void onItemClick(Object o, int position) {
        // TODO Auto-generated method stub
        if ((HSDialog) o == dialog_down) {
            if (position != -1) {
                // TODO: 2017/9/28 非WiFi情况下的下载有问题
                downloadNewVersion(~0);
            } else {
                if (isHome) {
                    if (if_force) mBaseTabView.initializeError(TaskConstants.TASK_FINISH, "");
                }
            }
        } else if ((HSDialog) o == dialog_update) {
            if (position != -1) {
                checkNetwork();
            } else {
                if (isHome) {
                    if (if_force) mBaseTabView.initializeError(TaskConstants.TASK_FINISH, "");
                }
            }
            mConfigSP.putBoolean("isfirstcheckversion",false);
        }
    }

    /**
     * 下载状态观察者
     */
    protected class DownloadChangeObserver extends ContentObserver {

        public DownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            queryDownloadStatus(downloadId);
        }
    }

    public void openFile(File file, Context context) {
        Intent intent = new Intent();
        intent.addFlags(268435456);
        intent.setAction("android.intent.action.VIEW");
        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(context, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }

    }

    public String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }
}
